// 人员选择
App.directive('edLineStops', ['$rootScope', '$compile', 'Page','$timeout', function ($rootScope, $compile, Page,$timeout) {
    return {

        restrict: 'A',
        templateUrl: 'views/line/lineStops.html',

        controller: ['$scope', '$element', function ($scope, $element) {

            $scope.AmapObject = {
                defaultWeidu : 30.595444,
                defaultJingdu : 114.296308,
                mapContainer : 'lineDesignMapContainer',
                init : function(stops){
                    this.num = 0;
                    this.stops = angular.copy(stops) || [];
                    this.stopMarkers = [];
                    this.editor = {};
                    this.sections = [];

                    this.map = new AMap.Map(this.mapContainer, {
                        resizeEnable: true,
                        zoom:13,
                        center: [this.defaultJingdu, this.defaultWeidu]
                    });

                    $(this.stops).each(function(idx, stop) {
                        stop.id = $scope.AmapObject.num++;
                        stop.weidu = stop.weidu || $scope.AmapObject.defaultWeidu;
                        stop.jingdu = stop.jingdu || $scope.AmapObject.defaultJingdu;
                    });

                    this.drawLine();
                },
                drawLine : function(){
                    $(this.sections).each(function(idx, section) {
                        section.lineEditor.close();
                        $scope.AmapObject.map.remove(section.line);
                    });
                    $(this.stopMarkers).each(function(idx, marker) {
                        $scope.AmapObject.map.remove(marker);
                    });

                    this.sections = [];
                    this.stopMarkers = [];
                    $(this.stops).each(function(idx, stop) {
                        if(stop.stopType != '0'){
                            //$scope.AmapObject.stopMarkers.push($scope.AmapObject.createStopMarker(stop));
                            $scope.AmapObject.createStopMarker(stop);
                        }

                        var section = null;
                        if($scope.AmapObject.sections.length == 0){
                            section = {
                                id: $scope.AmapObject.num++
                            };
                            $scope.AmapObject.sections.push(section);
                        } else{
                            if($scope.AmapObject.sections[$scope.AmapObject.sections.length - 1].start
                                && $scope.AmapObject.sections[$scope.AmapObject.sections.length - 1].end){
                                section = {
                                    id: $scope.AmapObject.num++,
                                    start : $scope.AmapObject.sections[$scope.AmapObject.sections.length - 1].end
                                };
                                $scope.AmapObject.sections.push(section);
                            }else{
                                section = $scope.AmapObject.sections[$scope.AmapObject.sections.length - 1]
                            }
                        }

                        if(stop.stopType == '0'){
                            if(!section.start){
                                return;
                            }else {
                                section.path = section.path || [];
                                section.path.push(stop);
                            }
                        }else if(!section.start){
                            section.start = stop;
                        }else if(!section.end){
                            section.end = stop;
                        }
                    }),
                        $($scope.AmapObject.sections).each(function(idx, section) {
                            $scope.AmapObject.createSectionPoly(section);
                        });

                    this.map.setFitView();
                    this.map.setZoom(13);
                },
                getSectionPath : function(section){
                    var path = [];
                    if(section.start){
                        path.push([section.start.jingdu,section.start.weidu]);
                    }
                    $(section.path).each(function(idx, stop) {
                        path.push([stop.jingdu,stop.weidu]);
                    });
                    if(section.end){
                        path.push([section.end.jingdu,section.end.weidu]);
                    }
                    return path;
                },
                createSectionPoly : function(section,path){
                    AMap.service(["AMap.PolyEditor"], function() {
                        section.line =(function(){
                            return new AMap.Polyline({
                                map: $scope.AmapObject.map,
                                path: path || $scope.AmapObject.getSectionPath(section),
                                strokeColor: "#FF33FF",//线颜色
                                strokeOpacity: 1,//线透明度
                                strokeWeight: 3,//线宽
                                strokeStyle: "solid",//线样式
                                showDir:true,
                                lineJoin:'round'
                            });
                        })();
                        section.lineEditor = new AMap.PolyEditor($scope.AmapObject.map, section.line);
                        section.lineEditor.open();
                    });
                },
                getStopMarkerContent : function(stop){
                	var content = '<img src="./assets/admin/img/dd-via.png"></img>'
                	 + '<div style="background-color:#ff0000;color:#fff;width:13px;font-size:14px;line-height:16px;">'
                	 + stop.stopName
                	 + '</div>';
                   return content;
                },
                createStopMarker : function(stop){
//                	  script：http://webapi.amap.com/ui/1.0/main.js
//                	  AMapUI.loadUI(['overlay/SvgMarker'], function(SvgMarker) {
//                		   var shape = new SvgMarker.Shape.Circle({
//			                    height: 24,
//			                    strokeWidth: 1,
//			                    strokeColor: '#ccc',
//			                    fillColor: 'red'
//			                });
//                		    var labelCenter = shape.getCenter();
//	                		 var marker1 = new SvgMarker(
//		                    	shape, 
//		                    	{
//			                        map: $scope.AmapObject.map,
//			                        position: [stop.weidu, stop.jingdu],
//			                        iconLabel: {
//			                            innerHTML: stop.stopName || '请输入站点',
//			                            style: {
//			                                top: labelCenter[1] - 29 + 'px'
//			                            }
//			                        },
//			                        showPositionPoint: false
//		                    	}
//		                    );
//                	  });
                	  
                    var marker = new AMap.Marker({
                        position: [stop.jingdu,stop.weidu],
                        map:this.map,
                        draggable: true,
                        offset : new AMap.Pixel(-8,-8),
                        zIndex: 1100,
                        content:$scope.AmapObject.getStopMarkerContent(stop),
                        extData:stop
                    });
                    marker.on('dragging',function(e){
                        var lnglat = e.lnglat;
                        this.setPosition(new AMap.LngLat(lnglat.lng,lnglat.lat));
                        var stop = e.target.G.extData;
                        stop.weidu = lnglat.lat;
                        stop.jingdu = lnglat.lng;
                        $($scope.AmapObject.sections).each(function(idx, section) {
                            if(section.start && section.start.id == stop.id){
                                section.start.weidu = lnglat.lat;
                                section.start.jingdu = lnglat.lng;
                                var path = section.line.getPath();
                                var _path = [];
                                $(path).each(function(idx, c) {
                                    _path.push([c.lng,c.lat]);
                                });
                                _path.splice(0,1,[lnglat.lng,lnglat.lat]);
                                section.line.setPath(_path);
                            }
                            if(section.end && section.end.id == stop.id){
                                section.end.weidu = lnglat.lat;
                                section.end.jingdu = lnglat.lng;
                                var path = section.line.getPath();
                                var _path = [];
                                $(path).each(function(idx, c) {
                                    _path.push([c.lng,c.lat]);
                                });
                                _path.splice(-1,1,[lnglat.lng,lnglat.lat]);
                                section.line.setPath(_path);
                            }
                        });

                    });
                    this.stopMarkers.push(marker);
                    
                    return marker;
                },
                removeStopMarker : function(stop){
                    $(this.stopMarkers).each(function(idx, marker) {
                        var _stop = marker.getExtData();
                        if(_stop && _stop.id == stop.id){
                            $scope.AmapObject.map.remove(marker);
                            $scope.AmapObject.stopMarkers.splice(idx,1);
                            return false;
                        }
                    });
                },
                addStop : function(baseStop,n){
                    baseStop = baseStop || {};
                    n = n || -1;

                    var newStop = {
                        id : this.num ++,
                        stopId : '',
                        stopType : baseStop.stopType || '1',
                        stopName : '',
                        jingdu : $scope.AmapObject.defaultJingdu,
                        weidu : $scope.AmapObject.defaultWeidu,
                        address: '',
                        remark:'',
                        _edit : true
                    };
                    if($scope.AmapObject.stops.length == 0){
                        $scope.AmapObject.stops.push(newStop);
                    }else{
                        $(this.stops).each(function(idx, _stop) {
                            if(_stop.id == baseStop.id){
                                $scope.AmapObject.stops.splice(idx + (n <= 0 ? 0 : 1), 0, newStop);
                                return false;
                            }
                        });
                        if(n <= 0){//站前加入
                            $(this.sections).each(function(idx, section) {
                                if(section.end && section.end.id == baseStop.id){
                                    var path = section.line.getPath();
                                    var _path = [];
                                    $(path).each(function(idx, c) {
                                        _path.push([c.lng,c.lat]);
                                    });
                                    _path.splice(-1,1,[newStop.jingdu,newStop.weidu]);
                                    section.end = newStop;
                                    section.line.setPath(_path);
                                }
                            });
                            var section = {
                                id: $scope.AmapObject.num++,
                                start : newStop,
                                end : baseStop,
                                path : []
                            };
                            $scope.AmapObject.sections.push(section);
                            $scope.AmapObject.createSectionPoly(section);
                        }else{
                            $(this.sections).each(function(idx, section) {
                                if(section.start && section.start.id == baseStop.id){
                                    var path = section.line.getPath();
                                    var _path = [];
                                    $(path).each(function(idx, c) {
                                        _path.push([c.lng,c.lat]);
                                    });
                                    _path.splice(0,1,[newStop.jingdu,newStop.weidu]);
                                    section.start = newStop;
                                    section.line.setPath(_path);
                                }
                            });
                            var section = {
                                id: $scope.AmapObject.num++,
                                start : baseStop,
                                end : newStop,
                                path : []
                            };
                            $scope.AmapObject.sections.push(section);
                            $scope.AmapObject.createSectionPoly(section);
                        }
                    }

                    this.createStopMarker(newStop);


                },
                saveStop : function(stop){
                    if(stop.stopName != ''){
                        $(this.stopMarkers).each(function(idx, marker) {
                            var _stop = marker.getExtData();
                            if(_stop && _stop.id == stop.id){
                                marker.setContent($scope.AmapObject.getStopMarkerContent(stop));
                                return false;
                            }
                        });
                        stop._edit = false;
                    }
                },
                setStopType : function(stop,type){
                    stop.stopType = type;
                },
                editStop : function(stop){
                	stop._edit = true;
//                    if(this.tmpStop){
//                        $("#tmpStop").focus();
//                    }else{
//                        $timeout(function(){
//                            $scope.$apply(function () {
//                                $scope.AmapObject.tmpStop = stop;
//                            });
//                            $("#tmpStop").focus();
//                        },1)
//                    }
                },
                removeStop : function(stop){
                    $(this.stops).each(function(idx, _stop) {
                        if(_stop.id == stop.id){
                            $scope.AmapObject.stops.splice(idx, 1);
                            return false;
                        }
                    });

                    var preSection,postSection;
                    $(this.sections).each(function(idx, section) {
                        if(section.start && section.start.id == stop.id){
                            postSection = section;
                            $scope.AmapObject.sections.splice(idx, 1);
                            postSection.lineEditor.close();
                            $scope.AmapObject.map.remove(postSection.line);
                            return false;
                        }
                    });
                    $(this.sections).each(function(idx, section) {
                        if(section.end && section.end.id == stop.id){
                            preSection = section;
                            $scope.AmapObject.sections.splice(idx, 1);
                            preSection.lineEditor.close();
                            $scope.AmapObject.map.remove(preSection.line);
                            return false;
                        }
                    });
                    if(preSection && postSection){
                        var _path = [];

                        var prePath = preSection.line.getPath();
                        $(prePath).each(function(idx, c) {
                            _path.push([c.lng,c.lat]);
                        });
                        _path.splice(-1,1);

                        var postPath = postSection.line.getPath();
                        $(postPath).each(function(idx, c) {
                            if(idx != 0){
                                _path.push([c.lng,c.lat]);
                            }
                        });

                        var section = {
                            id: $scope.AmapObject.num++,
                            start : preSection.start,
                            end : postSection.end,
                            path : angular.copy(preSection.path||[], postSection.path ||[])
                        };
                        $scope.AmapObject.sections.push(section);
                        $scope.AmapObject.createSectionPoly(section,_path);
                    }
                    $scope.AmapObject.removeStopMarker(stop);
                },
                getPath : function(){
                    var result = [];
                    $(this.stops).each(function(idx, stop) {
                        if(stop.stopType != '0'){
                            result.push(stop);
                            $($scope.AmapObject.sections).each(function(idx, section) {
                                if(section.start && section.start.id == stop.id){
                                    var paths = section.line.getPath();
                                    $(paths).each(function(idx, path) {
                                        if(idx != 0 && idx != paths.length - 1){
                                            result.push({
                                                stopName:'',
                                                stopType : 0,
                                                jingdu: path.lng,
                                                weidu: path.lat,
                                                address: '',
                                                remark:''
                                            });
                                        }
                                    });
                                }
                            });
                        }
                    });
                    return result;
                }
            }

            $scope.lineStops = {
                showStops: function (line) {
            		$scope.line = line;
                    Page.ajaxPost('line/stops.do', {lineId: line.lineId}, function (resp) {
                        $scope.lineMapModal.setTitle("　线路配置-【" + line.lineNo + "-" + line.lineName + "】");
                        $scope.lineMapModal.show();
                        $scope.AmapObject.init(resp.data);//  展示地图
                    });
                }
            }

            $scope.lineMapModal = {
                onOkClick : function(){
                    if($scope.AmapObject.tmpStop && $scope.AmapObject.tmpStop.stopName == ''){
                        Page.notice("请填写站点名称!");
                        return false;
                    }else{
                        var stops = $scope.AmapObject.getPath();
                        Page.ajaxPost('line/stop/update.do', {lineId:$scope.line.lineId,stopList:stops}, function (resp) {
                            Page.notice("站点信息保存成功!");
                        });
                    }
                },
                onHidden : function() {
                }
            };

        }],

        link: function (scope, elem, attrs, ngModelController) {
        }
    };
}]);